package com.dw.article.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dw.article.mapper.mp.CategoryInfoMapper;
import com.dw.article.utils.LoginUtil;
import com.dw.model.article.dtos.category.AddCategoryDTO;
import com.dw.model.article.dtos.category.AddCategoryHotDTO;
import com.dw.model.article.dtos.category.QueryCategoryDTO;
import com.dw.model.article.entitys.CategoryInfo;
import com.dw.article.service.CategoryInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 文章分类表(CategoryInfo)表服务实现类
 *
 * @author makejava
 * @since 2024-10-05 19:44:34
 */
@Service("categoryInfoService")
public class CategoryInfoServiceImpl extends ServiceImpl<CategoryInfoMapper, CategoryInfo> implements CategoryInfoService {

    @Resource
    private RedisTemplate redisTemplate;

    private final String CATEGORY_HOT = "category.hot";

    @Override
    public Boolean addCategory(AddCategoryDTO addCategoryDTO) {
        // 参数拷贝
        CategoryInfo categoryInfo = new CategoryInfo();
        BeanUtils.copyProperties(addCategoryDTO, categoryInfo);
        // 设置创建人
        categoryInfo.setCreatedBy(Long.valueOf(LoginUtil.getLoginId()));
        // 设置分类id
        long l = IdUtil.getSnowflake().nextId();
        categoryInfo.setLeiId(l);
        return save(categoryInfo);
    }

    @Override
    public List<CategoryInfo> queryCategoryByIds(List<Long> categoryIds) {
        return categoryIds.stream().map(item -> {
            CategoryInfo one = lambdaQuery()
                    .eq(CategoryInfo::getLeiId, item)
                    .one();
            return one;
        }).collect(Collectors.toList());
    }

    /**
     * 条件分页查询所有分类
     */
    @Override
    public List<CategoryInfo> queryCategory(QueryCategoryDTO queryCategoryDTO) {
        // 条件查询
        List<CategoryInfo> categoryInfos = lambdaQuery()
                .like(CategoryInfo::getCategoryName, queryCategoryDTO.getCategoryName())
                .list();
        // 分页查询
        List<List<CategoryInfo>> partition = Lists.partition(categoryInfos, queryCategoryDTO.getPageSize());
        return partition.get(queryCategoryDTO.getCurrent() - 1);

    }

    /**
     * 根据分类id查询分类名称
     */
    @Override
    public CategoryInfo queryCategoryNameById(Long categoryId) {
        return lambdaQuery()
                .eq(CategoryInfo::getLeiId, categoryId)
                .one();

    }

}

